package com.springboot.messagewall.controller;


import com.springboot.messagewall.model.MessageInfo;
import com.springboot.messagewall.service.MessageInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-03-23
 * Time: 14:31
 */
@RequestMapping("/message")
@RestController
public class MessageInfoController {

    @Autowired
    private MessageInfoService messageInfoService;

    @PostMapping("/publish")
    public String publish(@RequestBody MessageInfo messageInfo) {
        // 1、检验参数是否合法
        if (messageInfo == null) {
            System.out.println("message对象为null");
            return "{\"OK\": 0}";
        }
        if (!StringUtils.hasLength(messageInfo.getFrom())) {
            System.out.println("message对象的from为空");
            return "{\"OK\": 0}";
        }
        if (!StringUtils.hasLength(messageInfo.getTo())) {
            System.out.println("message对象的to为空");
            return "{\"OK\": 0}";
        }
        if (!StringUtils.hasLength(messageInfo.getMessage())) {
            System.out.println("message对象的message为空");
            return "{\"OK\": 0}";
        }
        // 2、插入新留言到数据库中
        try {
            messageInfoService.insertMessageInfo(messageInfo);
        } catch (Exception e) {
            System.out.println("留言插入失败");
            return "{\"OK\": 0}";
        }
        System.out.println("插入留言成功");
        return "{\"OK\": 1}";
    }

    @GetMapping("/getList")
    public List<MessageInfo> getList() {
        try {
            List<MessageInfo> messageInfos = messageInfoService.selectAllMessage();
            System.out.println("留言获取成功");
            return messageInfos;
        } catch (Exception e) {
            System.out.println("留言获取失败");
            return null;
        }
    }

    @PostMapping("/deleteMessage")
    public String deleteMessage(String username, String password, @RequestBody MessageInfo messageInfo) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            System.out.println("留言删除失败");
            return "{\"OK\": 0}";
        }
        if (!"我要学编程".equals(username) || !"123456".equals(password)) {
            System.out.println("留言删除失败");
            return "{\"OK\": 0}";
        }
        try {
            messageInfoService.deleteMessage(messageInfo);
        } catch (Exception e) {
            System.out.println("删除失败");
            return "{\"OK\": 0}";
        }
        return "{\"OK\": 1}";
    }
}
